package cn.edu.njupt.post.dao;

import cn.edu.njupt.post.model.Post;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface PostDAO {
    String TABLE_NAME = " post ";
    String INSERT_FIELDS = " title, content, created_date, user_id, comment_count ";
    String SELECT_FIELDS = " id, " + INSERT_FIELDS;

    @Insert({"insert into ", TABLE_NAME, "(", INSERT_FIELDS,
            ") values (#{title},#{content},#{createdDate},#{userId},#{commentCount})"})
    int addPost(Post post);

    @Select({"select ", SELECT_FIELDS, " from ", TABLE_NAME, " order by id desc limit #{offset},#{limit}"})
    List<Post> selectLatestPosts(@Param("offset") int offset,
                                       @Param("limit") int limit);
    @Select({"select ", SELECT_FIELDS, " from ", TABLE_NAME, " order by comment_count desc limit #{offset},#{limit}"})
    List<Post> selectHotPosts(@Param("offset") int offset,
                                 @Param("limit") int limit);


    @Select({"select ", SELECT_FIELDS, " from ", TABLE_NAME, " where user_id=#{userId} order by id desc limit #{offset},#{limit}"})
    List<Post> selectLatestPostsByUser(@Param("userId") int userId, @Param("offset") int offset,
                                 @Param("limit") int limit);




    @Select({
            "<script>",
            "select ", SELECT_FIELDS, " from ", TABLE_NAME,
            "        <if test='userIds.size() != 0'>" ,
            "     where user_id in" ,
            "            <foreach item='item'  collection='userIds'" ,
            "    open='(' separator=',' close=')'>" ,
            "            #{item}" ,
            "            </foreach>" ,
            "        </if>" ,
            "    ORDER BY id DESC" ,
            "    LIMIT #{count}" ,
            "    </script>"})
    List<Post> selectLatestPostsByUsers(@Param("userIds") List<Integer> userIds, @Param("count") int count);

    @Select({"select ", SELECT_FIELDS, " from ", TABLE_NAME, " where id=#{id}"})
    Post getById(int id);

    @Update({"update ", TABLE_NAME, " set comment_count = #{commentCount} where id=#{id}"})
    int updateCommentCount(@Param("id") int id, @Param("commentCount") int commentCount);

    @Select({" select count(id) from ", TABLE_NAME})
    int getPostCount();

    @Select({" select count(id) from ", TABLE_NAME, "where user_id=#{userId}"})
    int getPostCountById(@Param("userId") int userId);

    @Delete({" delete from", TABLE_NAME, "where id=#{id}"})
    int deleteById(@Param("id") int id);

}
